package com.ely.coupon.auth.service;

import com.ely.coupon.auth.feign.MemberService;
import com.ely.coupon.common.core.ex.ServiceException;
import com.ely.coupon.common.core.result.ResponseCode;
import com.ely.coupon.common.core.result.ResponseResult;
import com.ely.coupon.member.api.MemberApi;
import com.ely.coupon.member.dto.MemberDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private MemberService memberService;

    // 远程调用
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResponseResult<MemberDTO> result = memberService.getMemberInfo(username);
        if (result.getCode() != 200) {
            throw new ServiceException(ResponseCode.SYS_ERROR);
        }
        MemberDTO member = result.getData();
        if (ObjectUtils.isEmpty(member)) {
            throw new ServiceException(ResponseCode.ACCOUNT_NOT_EXIST);
        }
        return new User(member.getMemberName(), member.getPassword(), new ArrayList<>());
    }
}
